<template>
  <baidu-map class="map" :map-type="mapType" :center="center" :zoom="zoom" :scroll-wheel-zoom="true" @ready="handler" @zoomend="zoomend">
    <myOverlay v-for="(item, index) in pList" :key="index" :ref="`myoverlay${item.id}`" :row="item" :position="{lng: item.lon, lat: item.lat}" :text="item.index" @click.native="infoWindowOpen(item)" />
    <bm-polyline :path="pathLushu" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="4" :editing="false" />
    <bml-lushu :path="pathLushu" :icon="icon" :play="play" :rotation="true" :speed="speed" @stop="pause" />
    <div class="map-type">
      <div :class="mapType === 'BMAP_NORMAL_MAP' ? 'type-item type-item1 type-active' : 'type-item type-item1'" @click="changeMapType('BMAP_NORMAL_MAP')">平面图</div>
      <div :class="mapType === 'BMAP_HYBRID_MAP' ? 'type-item type-item2 type-active' : 'type-item type-item2'" @click="changeMapType('BMAP_HYBRID_MAP')">卫星图</div>
    </div>
    <el-collapse-transition>
      <div v-show="showSide" class="side-info">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="当前车况" name="first">
            <div class="vehicle-condition">
              <el-descriptions size="medium" :label-style="labelStyle" :content-style="contentStyle" :column="1">
                <el-descriptions-item label="GPS状态">{{ currentInfo.onlineStatus ? '在线' : '离线' }}</el-descriptions-item>
                <el-descriptions-item label="当前位置">{{ currentInfo.onlineStatus ? currentInfo.location : '' }}</el-descriptions-item>
                <el-descriptions-item label="定位时间">{{ currentInfo.onlineStatus && currentInfo.locTime ? parseTime(currentInfo.locTime, '{y}-{m}-{d} {h}:{m}:{s}') : '' }}</el-descriptions-item>
                <el-descriptions-item label="今日里程">{{ currentInfo.onlineStatus && currentInfo.dayMileage ? currentInfo.dayMileage/1000 + 'KM' : '' }}</el-descriptions-item>
                <!-- <el-descriptions-item label="今日在线时长">{{ '' }}</el-descriptions-item>
                <el-descriptions-item label="今日报警信息">{{ currentInfo.onlineStatus && currentInfo.alarmFenceProperties ? currentInfo.alarmFenceProperties : '' }}</el-descriptions-item> -->
              </el-descriptions>
              <el-button class="refresh-btn" type="primary" size="mini" @click="refresh">刷新</el-button>
            </div>
            <div class="vehicle-trail">
              <div class="trail-title">配送轨迹</div>
              <div class="search-box">
                <div class="search-label">选择日期：</div>
                <el-date-picker v-model="dateSearch" type="date" placeholder="选择日期" style="width: 140px;" />
                <el-button class="search-btn" type="primary" size="mini" @click="search">查询</el-button>
              </div>
              <el-tabs v-model="orderTab">
                <el-tab-pane label="待办订单" name="first">
                  <lb-table
                    ref="lbTable"
                    border
                    highlight-current-row
                    element-loading-text="加载中"
                    size="mini"
                    :column="tableData.column"
                    :data="tableData.data"
                    :total="tableData.total"
                    @fetch="fetchData"
                  />
                </el-tab-pane>
                <el-tab-pane label="配送订单" name="second">
                  <lb-table
                    ref="lbTable2"
                    border
                    highlight-current-row
                    element-loading-text="加载中"
                    size="mini"
                    :column="tableData2.column"
                    :data="tableData2.data"
                    :total="tableData2.total"
                    @fetch="fetchData2"
                  />
                </el-tab-pane>
                <el-tab-pane label="报警信息" name="third">
                  <el-table size="mini" :data="tableData3" style="width: 100%;">
                    <el-table-column prop="index" label="#" width="50" />
                    <el-table-column prop="name" label="订单编号" show-overflow-tooltip width="120" />
                    <el-table-column prop="address" show-overflow-tooltip label="地址" />
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="'车载气瓶('+tableData4.total+')'" name="second">
            <lb-table
              ref="lbTable4"
              border
              highlight-current-row
              element-loading-text="加载中"
              size="mini"
              :column="tableData4.column"
              :data="tableData4.data"
              :total="tableData4.total"
              @fetch="fetchData4"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-collapse-transition>
    <div :class="showSide ? 'side-btn side-btn1':'side-btn side-btn2'" @click="changeSide">
      <span v-if="showSide" class="el-icon-arrow-left">收起</span>
      <span v-else>
        展开<i class="el-icon-arrow-right" />
      </span>
    </div>
    <!-- 右下控件 -->
    <bm-control v-show="pathLushu.length" anchor="BMAP_ANCHOR_BOTTOM_RIGHT">
      <div class="speed-container">
        <div class="drawing-panel" style="z-index: 99;">
          <p class="btn" @click="lushuStart">开始</p>
          <p class="btn" @click="pause">暂停</p>
          <!-- <p class="btn" @click="stop">停止</p> -->
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              {{ handleSpeed }}<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(item,index) in speedList" :key="index" :command="item.command">{{ item.label }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </bm-control>
    <cylinderDetail ref="cylinderDetail" />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
  </baidu-map>
</template>

<script>
  import { BmlLushu } from 'vue-baidu-map'
  import myOverlay from './myOverlay.vue'
  import { parseTime } from '@/utils'
  import { queryVehicleOrder, gpsDevice, queryOrderDetailData, gpsTrack, bottleList, queryMap, queryTransactorList } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import CylinderDetail from '@/views/components/cylinderDetail/index'
  import OrderDetail from '../../../orderCenter/orderManage/components/OrderDetails.vue'

  export default {
    name: 'vehicleMap',
    components: {
      BmlLushu, myOverlay, CylinderDetail, OrderDetail
    },
    props: {
      truckCode: {
        type: String
      },
      driverId: {
        type: Number
      }
    },
    data() {
      return {
        parseTime: parseTime,
        zoom: 11,
        center: null,
        activeTab: 'first',
        orderTab: 'first',
        mapType: 'BMAP_NORMAL_MAP',
        dateSearch: new Date(),
        labelStyle: { 'white-space': 'nowrap' },
        contentStyle: { 'word-break': 'break-all' },
        currentInfo: {},
        pList: [],
        paymentMethodMap: [],
        payStatusMap: [],
        transactorList: [],
        orderFlagMap: [],
        orderSourceMap: [],
        orderStatusMap: [],
        currentOrder: {},
        orderInfo: {},
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'orderCode',
              label: '订单编号',
              width: 80,
              render: (h, { row }) => (
                <el-link underline={false} onClick={() => this.openOrderDetail(row)}>
                  {row.orderCode}
                </el-link>
              )
            },
            {
              prop: 'csmAddress',
              label: '地址',
              showOverflowTooltip: true,
              render: (h, { row }) => {
                return (
                <span>
                  <span class='point-span'>
                    { row.lon && row.lat && (
                      <i
                        onClick={() => this.infoWindowOpen(row)}
                        class='linkColor el-icon-location'
                        style='cursor: pointer; color: #E86F00'
                      />
                    )}
                  </span>
                  <span>{row.csmAddress}({row.lon},{row.lat})</span>
                </span>
                )
              }
            }
          ],
          data: []
        },
        tableData2: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'orderCode',
              label: '订单编号',
              width: 80,
              render: (h, { row }) => (
                <el-link underline={false} onClick={() => this.openOrderDetail(row)}>
                  {row.orderCode}
                </el-link>
              )
            },
            {
              prop: 'csmAddress',
              label: '地址',
              showOverflowTooltip: true,
              render: (h, { row }) => {
                return (
                <span>
                  <span class='point-span'>
                    { row.lon && row.lat && (
                      <i
                        onClick={() => this.infoWindowOpen(row)}
                        class='linkColor el-icon-location'
                        style='cursor: pointer;'
                      />
                    )}
                  </span>
                  <span>{row.csmAddress}({row.lon},{row.lat})</span>
                </span>
                )
              }
            }
          ],
          data: []
        },
        tableData4: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'chipCode',
              label: '气瓶芯片号',
              render: (h, { row }) => (
              <el-link underline={false} onClick={() => this.openCylinderDetail(row.chipCode)}>
                {row.chipCode}
              </el-link>
              )
            },
            // {
            //   prop: '',
            //   label: '型号'
            // },
            {
              prop: 'status',
              label: '气瓶状态',
              render: (h, { row }) => <span>{row.status === 1 ? '重瓶' : row.status === 2 ? '空瓶' : ''}</span>
            }
          ],
          data: []
        },
        tableData3: [],
        cylinderData: [
          {
            chipCode: 'DFG123213',
            chipType: '15型',
            chipStatus: '重瓶'
          },
          {
            chipCode: 'DFG123213',
            chipType: '15型',
            chipStatus: '重瓶'
          },
          {
            chipCode: 'DFG123213',
            chipType: '15型',
            chipStatus: '重瓶'
          },
          {
            chipCode: 'DFG123213',
            chipType: '15型',
            chipStatus: '重瓶'
          },
          {
            chipCode: 'DFG123213',
            chipType: '15型',
            chipStatus: '重瓶'
          }
        ],
        carInfo: {
          carId: '',
          deliveryClerk: '',
          accStatus: '',
          location: '',
          locationTime: '',
          warnStatus: '',
          mileage: ''
        },
        showSide: true,
        speed: 1000,
        speedList: [
          {
            label: 'X 1',
            command: 1000
          },
          {
            label: 'X 2',
            command: 2000
          },
          {
            label: 'X 3',
            command: 3000
          },
          {
            label: 'X 4',
            command: 4000
          },
          {
            label: 'X 5',
            command: 5000
          }
        ],
        play: true,
        path: [],
        icon: {
          url: require('@/assets/car-blue.png'),
          size: { width: 50, height: 40 },
          opts: { anchor: { width: 25, height: 20 }}
        },
        pathLushu: [],
        infoWindow: {
          show: false,
          contents: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
        },
        moveNum: 1
      }
    },
    computed: {
      positionList() {
        return this.tableData.data.concat(this.tableData2.data)
      },
      handleSpeed() {
        return this.speedList.find(item => item.command === this.speed).label || ''
      }
    },
    watch: {
      positionList: {
        handler(val) {
          this.pList = val
          this.pList.forEach((item, index) => {
            item.id = parseInt(index + 1)
          })
        },
        immediate: true
      }
    },
    mounted() {
      this.queryOptionsMap()
      this.getTransactorList()
    },
    methods: {
      handler({ BMap, map }) {
        this.BMap = BMap
        this.map = map
        this.gpsDevice()
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.orderSourceMap = res7.data // 订单来源
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      async openOrderDetail(row) {
        const orderDetail = document.getElementsByClassName('orderDetail')[0]
        if (!orderDetail) {
          await this.$refs.orderDetail.open(row, true)
        } else {
          this.$message.warning('该信息弹窗已存在，请关闭当前弹窗')
        }
      },
      // 获取当前车况
      async gpsDevice() {
        const res = await gpsDevice({ truckCode: this.truckCode })
        this.currentInfo = res.data
        if (this.currentInfo.lat && this.currentInfo.lon) {
          this.center = { lat: this.currentInfo.lat, lng: this.currentInfo.lon }
          const geoc = await new this.BMap.Geocoder()
          const pointNew = new this.BMap.Point(this.currentInfo.lon, this.currentInfo.lat)
          await geoc.getLocation(pointNew, (res) => {
            if (res && res.address) {
              this.currentInfo.location = res.address
            } else {
              this.currentInfo.location = ''
            }
          })
        } else {
          this.center = '北京'
        }
        if (this.currentInfo.deviceNo) {
          this.getLushuData(this.currentInfo.deviceNo)
        }
      },
      // 获取代办订单
      async fetchData({ currentPage, pageSize }) {
        const query = {
          truckCode: this.truckCode,
          ck: 1,
          queryDt: parseTime(this.dateSearch, '{y}-{m}-{d}'),
          pageIndex: currentPage,
          pageSize: 9999
        }
        const res = await queryVehicleOrder(query)
        if (res.data && res.data.rows) {
          this.tableData.data = res.data.rows
          this.tableData.data.forEach((item, index) => {
            item.type = 'wait'
            item.index = parseInt(index + 1)
          })
          this.tableData.total = res.data.total
        }
      },
      // 获取配送订单
      async fetchData2({ currentPage, pageSize }) {
        const query = {
          truckCode: this.truckCode,
          ck: 2,
          queryDt: parseTime(this.dateSearch, '{y}-{m}-{d}'),
          pageIndex: currentPage,
          pageSize: 9999
        }
        const res = await queryVehicleOrder(query)
        if (res.data && res.data.rows) {
          this.tableData2.data = res.data.rows
          this.tableData2.total = res.data.total
          this.tableData2.data.forEach((item, index) => {
            item.index = parseInt(index + 1)
          })
        }
      },
      // 获取车载气瓶
      async fetchData4({ currentPage, pageSize }) {
        const query = {
          driverId: this.driverId,
          currentPage,
          pageSize: 1000
        }
        const res = await bottleList(query)
        if (res.data && res.data.rows) {
          this.tableData4.data = res.data.rows
          this.tableData4.total = res.data.total
        }
      },
      // 查看气瓶流转
      openCylinderDetail(chipCode) {
        this.$refs.cylinderDetail.open(chipCode, '')
      },
      // 获取lushu数据
      async getLushuData(deviceNo) {
        const res = await gpsTrack({ deviceNo, beginTime: parseTime(this.dateSearch, '{y}-{m}-{d}') + ' 00:00:00', endTime: parseTime(this.dateSearch, '{y}-{m}-{d}') + ' 23:59:59' })
        res.data.forEach(item => {
          this.pathLushu.push(new this.BMap.Point(item.lon, item.lat))
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
        this.$refs.lbTable2.fetch({ currentPage: 1 })
      },
      refresh() {
        this.gpsDevice()
      },
      changeMapType(type) {
        this.mapType = type
      },
      changeSide() {
        this.showSide = !this.showSide
      },
      // 速度调整
      handleCommand(command) {
        this.speed = command
      },
      lushuStart() {
        this.play = true
      },
      pause() {
        this.play = false
      },
      stop() {
        this.play = false
      },
      infoWindowClose(e) {
        this.infoWindow.show = false
      },
      zoomend() {
        if (this.map) {
          this.zoom = this.map.getZoom()
        }
      },
      async infoWindowOpen(item) {
        console.log(item)
        if (item.orderCode) {
          const res = await queryOrderDetailData({ orderCode: item.orderCode })
          this.orderInfo = res.data
          this.currentOrder = item
          this.pList.forEach(it => {
            this.$refs[`myoverlay${it.id}`][0].active = false
          })
          if (!this.pList.some(it => it.id === item.id)) {
            this.pList.push(item)
          }
          this.center = ''
          this.$nextTick(() => {
            this.$refs[`myoverlay${item.id}`][0].active = true
            this.$refs[`myoverlay${item.id}`][0].getData(this.orderInfo)
            this.center = { lng: item.lon, lat: item.lat }
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .map {
    position: relative;
    width: 100%;
    height: 650px;
    .map-type {
      position: absolute;
      top: 20px;
      right: 20px;
      display: flex;
      .type-item {
        padding: 3px 7px;
        background-color: white;
      }
      .type-item1 {
        border-bottom-left-radius: 10px;
        border-top-left-radius: 10px;
      }
      .type-item2 {
        border-top-right-radius: 10px;
        border-bottom-right-radius: 10px;
      }
      .type-active {
        font-weight: 500;
        color: white;
        background-color: #8EA8E0;
      }
    }
    .side-info {
      position: absolute;
      top: 20px;
      left: 20px;
      width: 320px;
      height: 600px;
      padding: 10px;
      overflow: auto;
      background-color: white;
      .vehicle-trail {
        /deep/.el-pagination__jump {
          display: none;
        }
        // /deep/.el-table {
        //   height: 200px !important;
        // }
        // /deep/.el-table__body-wrapper {
        //   height: 150px !important;
        // }
      }
    }
    .refresh-btn {
      position: absolute;
      top: 0;
      right: 0;
    }
    .vehicle-trail {
      margin-top: 5px;
      .trail-title {
        height: 35px;
        font-size: 16px;
        line-height: 35px;
        border-bottom: 2px solid #DCDFE6;
      }
      .search-box {
        display: flex;
        margin-top: 10px;
        .search-label {
          line-height: 32px;
        }
        .search-btn {
          margin-left: 10px;
        }
      }
    }
    .side-btn {
      position: absolute;
      top: 20px;
      padding: 5px 10px;
      color: white;
      background-color: #01999F;
      border-radius: 5px;
    }
    .side-btn1 {
      left: 345px;
    }
    .side-btn2 {
      left: 20px;
    }
    .speed-container {
      padding: 10px;
      .drawing-panel {
        z-index: 999;
        padding: 1rem 1rem;
        margin-left: 8px;
        background-color: #fff;
        border-radius: 0.25rem;
        box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
      }
      .btn {
        float: left;
        width: 90px;
        height: 30px;
        margin: 0 5px;
        font-size: 14px;
        line-height: 30px;
        color: rgba(27, 142, 236, 1);
        text-align: center;
        background-color: #fff;
        border: 1px solid rgba(27, 142, 236, 1);
        border-radius: 5px;
      }
      .btn:hover {
        color: #fff;
        background-color: rgba(27, 142, 236, 0.8);
      }
    }
  }
  .link-text {
    color: #38BDBD;
    cursor: pointer;
  }
</style>
